package com.quanyan.user.service.impl;

import com.quanyan.common.constants.Constants;
import com.quanyan.common.enums.CommonParameterEnum;
import com.quanyan.common.utils.StringUtil;
import com.quanyan.user.cache.Cache;
import com.quanyan.user.cache.MyRedisTemplate;
import com.quanyan.user.constants.UserConstants;
import com.quanyan.user.mapper.*;
import com.quanyan.user.model.db.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * Created by zhang on 16/7/3.
 */
public class UserBaseServiceImpl {

    private final Logger logger = LoggerFactory.getLogger(UserBaseServiceImpl.class);
    @Autowired
    private TbUserMedalRelationMapper userMedalRelationMapper;
    @Autowired
    private TbProvinceMapper provinceMapper;
    @Autowired
    private TbCityMapper cityMapper;
    @Autowired
    private TbCommonParameterMapper commonParameterMapper;
    @Autowired
    private TbUserMapper userMapper;
    @Autowired
    private TbUserAccountRelationMapper userAccountRelationMapper;
    @Autowired
    private TbImDetailsMapper imDetailsMapper;
    @Autowired
    private MyRedisTemplate myRedisTemplate;
    @Autowired
    private TbUserThirdAccountMapper userThirdAccountMapper;
    @Autowired
    private UserThirdAccountExtendMapper userThirdAccountExtendMapper;

    /**
     * 用户徽章总数
     * @param uid
     * @return
     */
    public int getUserMedalCount(int uid){
        TbUserMedalRelationExample example = new TbUserMedalRelationExample();
        TbUserMedalRelationExample.Criteria criteria = example.createCriteria();
        criteria.andUidEqualTo(uid);
        criteria.andMedalStartLevelGreaterThan((byte)0);
        criteria.andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        int count = this.userMedalRelationMapper.countByExample(example);
        return count;
    }


    /**
     * 获取省信息
     * @param provinceId
     * @return
     */
    public List<TbProvince> getProvinceList(int provinceId){
        TbProvinceExample example = new TbProvinceExample();
        TbProvinceExample.Criteria criteria = example.createCriteria();
        if(provinceId != 0){
            criteria.andIdEqualTo(provinceId);
        }
        example.setOrderByClause("priority asc");
        List<TbProvince> list = this.provinceMapper.selectByExample(example);
        return list;
    }

    /**
     * 获取市信息
     * @param provinceId
     * @return
     */
    public List<TbCity> getCityList(int provinceId,int cityId){
        TbCityExample example = new TbCityExample();
        TbCityExample.Criteria criteria = example.createCriteria();
        if(provinceId != 0){
            criteria.andProvinceIdEqualTo(provinceId);
        }
        if(cityId != 0){
            criteria.andIdEqualTo(cityId);
        }
        example.setOrderByClause("priority asc");
        List<TbCity> list = this.cityMapper.selectByExample(example);
        return list;
    }


    /**
     * 获取用户公共参数
     * @param parameterKey
     * @return
     */
    public List<TbCommonParameter> getCommonParameterList(String parameterKey,String extendInfo){
        List<TbCommonParameter> commonParameterList = new ArrayList<>();
        if (!StringUtils.isBlank(parameterKey) && !StringUtils.isBlank(extendInfo)) {
            TbCommonParameter commonParameter = (TbCommonParameter) myRedisTemplate.hget(UserConstants.getCommonParamKey(parameterKey),UserConstants.getCommonParamExtend(extendInfo));
            if (commonParameter != null) {
                commonParameterList.add(commonParameter);
            } else {
                TbCommonParameterExample example = new TbCommonParameterExample();
                TbCommonParameterExample.Criteria criteria = example.createCriteria();
                criteria.andParameterKeyEqualTo(parameterKey);
                criteria.andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
                criteria.andExtendInfoEqualTo(extendInfo);
                commonParameterList = this.commonParameterMapper.selectByExample(example);
                if (!commonParameterList.isEmpty()) {
                    myRedisTemplate.hset(
                            UserConstants.getCommonParamKey(parameterKey),
                            UserConstants.getCommonParamExtend(extendInfo),
                            commonParameterList.get(0));
                }
            }
        } else {
            TbCommonParameterExample example = new TbCommonParameterExample();
            TbCommonParameterExample.Criteria criteria = example.createCriteria();
            criteria.andParameterKeyEqualTo(parameterKey);
            criteria.andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
            if (extendInfo != null) {
                criteria.andExtendInfoEqualTo(extendInfo);
            }
            commonParameterList = this.commonParameterMapper.selectByExample(example);
        }
        return commonParameterList;
    }

    /**
     * 随机获取个人背景图片
     * @return
     */
    public String getRandomBgUrl(){
        List<TbCommonParameter> commonParameterList = this.getCommonParameterList(CommonParameterEnum.USER_SYSTEM_BG.getCode(),null);
        int k;
        if (!commonParameterList.isEmpty()) {
            k = new Random().nextInt(commonParameterList.size());
            return commonParameterList.get(k).getParameterValue();
        } else {
            return "";
        }
    }

    /**
     * 通过手机号从数据库中获取用户信息
     * @param mobile 手机号
     * @return
     */
    public TbUser getUserToDbByPhone(String mobile){
        TbUserExample example = new TbUserExample();
        TbUserExample.Criteria criteria = example.createCriteria();
        criteria.andMobileEqualTo(mobile);
        List<TbUser> userList = userMapper.selectByExample(example);
        if (userList.isEmpty()) {
            return null;
        } else {
            return userList.get(0);
        }
    }

    /**
     *通过ID从数据库中获取用户信息
     * @return
     */
    public TbUser getUserToDbByUid(Integer uid){
        TbUser user = userMapper.selectByPrimaryKey(uid);
        return user;
    }

    /**
     * 获取用户账户关联信息
     * @param type
     * @param openId
     * @param unionId
     * @return
     */
    public TbUserAccountRelation getUserAccountRelation(int type,String openId,String unionId){
        TbUserAccountRelationExample example = new TbUserAccountRelationExample();
        TbUserAccountRelationExample.Criteria criteria = example.createCriteria();
        criteria.andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        if (type == 1 ) {
            criteria.andOpenIdEqualTo(openId);
        }
        if (type == 2 ) {
            criteria.andUnionIdEqualTo(unionId);
        }
        List<TbUserAccountRelation> list = userAccountRelationMapper.selectByExample(example);
        if (list.isEmpty()) {
            return null;
        } else {
            return list.get(0);
        }
    }

    /**
     * 插入用户账号关联信息
     * @param type
     * @param openId
     * @param unionId
     * @param uid
     * @return
     */
    public int addUserAccountRelation(int type,String openId,String unionId,int uid){
        TbUserAccountRelation userAccountRelation = new TbUserAccountRelation();
        userAccountRelation.setOpenId(openId);
        userAccountRelation.setUnionId(unionId);
        userAccountRelation.setUid(uid);
        userAccountRelation.setType(type);
        int n = userAccountRelationMapper.insertSelective(userAccountRelation);
        return n;
    }

    /**
     * 通过手机号从数据库中获取用户信息
     * @param mobile 手机号
     * @return
     */
    public TbUser getUserToDb(String mobile,String qqOpenId,String weiboOpenId,String weixinAppOpenId,String weixinUnionId){
        TbUserExample example = new TbUserExample();
        TbUserExample.Criteria criteria = example.createCriteria();
        if (StringUtil.isNotBlank(mobile)) {
            criteria.andMobileEqualTo(mobile);
        }
        if (StringUtil.isNotBlank(qqOpenId)) {
            criteria.andQqOpenidEqualTo(qqOpenId);
        }
        if (StringUtil.isNotBlank(weiboOpenId)) {
            criteria.andWeiboOpenidEqualTo(weiboOpenId);
        }
        if (StringUtil.isNotBlank(weixinAppOpenId)) {
            criteria.andWeixinAppOpenidEqualTo(weixinAppOpenId);
        }
        if (StringUtil.isNotBlank(weixinUnionId)) {
            criteria.andWeixinUnionidEqualTo(weixinUnionId);
        }
        List<TbUser> userList = userMapper.selectByExample(example);
        if (userList.isEmpty()) {
            return null;
        } else {
            return userList.get(0);
        }
    }

    /**
     * 获取用户Im详情
     * @param uid
     * @return
     */
    public TbImDetails getImDetails(int uid){
        TbImDetailsExample example = new TbImDetailsExample();
        TbImDetailsExample.Criteria criteria = example.createCriteria();
        criteria.andUidEqualTo(uid);
        List<TbImDetails> imDetailsList = imDetailsMapper.selectByExample(example);
        if (!imDetailsList.isEmpty()) {
            return imDetailsList.get(0);
        } else {
            return null;
        }
    }

    /**
     * 获取客服列表
     * @return
     */
    public List<TbUser> getCommissionerList(){
        TbUserExample example = new TbUserExample();
        TbUserExample.Criteria criteria = example.createCriteria();
        criteria.andTypeEqualTo((byte) 2);
        criteria.andIsEnableEqualTo((byte)1);
        List<TbUser> commissionerList = userMapper.selectByExample(example);
        return commissionerList;
    }

    /**
     * 将推送信息存入redis中
     * @param uid
     * @param cid
     * @param token
     * @param devType
     * @return
     */
    public int setPushCache(int uid,String cid,String token,int devType,int appid){
        StringBuffer key = new StringBuffer();
        key.append("cache_").append(uid).append("_push");
        Cache.UserDevCache.Builder builder = Cache.UserDevCache.newBuilder();
        if (StringUtils.isBlank(cid)) {
            return 0;
        } else {
            builder.setCid(cid);
        }
        builder.setDevType(devType);
        if (StringUtils.isBlank(token)) {
            builder.setToken("");
        } else {
            builder.setToken(token);
        }
        builder.setIsaccept(1);
        builder.setUpdateTime(new Date().getTime());
        builder.setAppid(appid);
        Cache.UserDevCache userDevCache = builder.build();
        logger.info("推送缓存对象信息：key为：【{}】，缓存信息：{}", key.toString(), userDevCache.toString());
        Long l = myRedisTemplate.hsetProto(key.toString(), cid, userDevCache.toByteArray());
        return l.intValue();
    }

    /**
     * 更新用户账号关联信息
     * @param uid
     * @return 更新的个数
     */
    public int updateUserAccountRelation(int uid,String openId){
        TbUserAccountRelationExample example = new TbUserAccountRelationExample();
        TbUserAccountRelationExample.Criteria criteria = example.createCriteria();
        criteria.andUidEqualTo(uid);
        if (!StringUtils.isBlank(openId)) {
            criteria.andOpenIdEqualTo(openId);
        }
        criteria.andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        TbUserAccountRelation userAccountRelation = new TbUserAccountRelation();
        userAccountRelation.setIsDelete(Constants.IS_DELETE_TRUE);
        int n = userAccountRelationMapper.updateByExampleSelective(userAccountRelation, example);
        return n;
    }

    /**
     * 更新用户登陆时间
     * @param uid
     */
    @Async
    public void updateUserLoginTime(int uid) {
        TbUserExample example = new TbUserExample();
        TbUserExample.Criteria criteria = example.createCriteria();
        criteria.andIdEqualTo(uid);

        TbUser record = new TbUser();
        record.setLoginTime(new Date());

        userMapper.updateByExampleSelective(record, example);
    }

    /**
     * 账户关联信息
     * @param larkAppId
     * @param unionOrOpen
     * @param type
     * @return
     */
    public List<TbUserAccountRelation> getUserAccountList(int larkAppId,String unionOrOpen, int type){
        TbUserAccountRelationExample example = new TbUserAccountRelationExample();
        TbUserAccountRelationExample.Criteria criteria = example.createCriteria();
        if (UserConstants.AccountType.WECHAT_OPEND_ID_TYPE == type) {
            criteria.andOpenIdEqualTo(unionOrOpen);
        }
        if (UserConstants.AccountType.WECHAT_UNION_ID_TYPE == type) {
            criteria.andUnionIdEqualTo(unionOrOpen);
        }
        criteria.andLarkAppIdEqualTo(larkAppId);
        criteria.andIsDeleteEqualTo(UserConstants.IS_DELETE_Y);
        List<TbUserAccountRelation> userAccountRelationList = userAccountRelationMapper.selectByExample(example);
        return userAccountRelationList;
    }

    /**
     * 获取账号绑定信息
     * @param uid
     * @param larkAppId
     * @param unionId
     * @param openId
     * @return
     */
    public List<TbUserThirdAccount> getUserThirdAccountList(Integer uid,Integer larkAppId,String unionId,String openId,int type){
        TbUserThirdAccountExample example = new TbUserThirdAccountExample();
        TbUserThirdAccountExample.Criteria criteria = example.createCriteria();
        if (uid != null) {
            criteria.andUidEqualTo(uid);
        }
        if (larkAppId != null) {
            criteria.andLarkAppIdEqualTo(larkAppId);
        }
        if (StringUtils.isNotBlank(unionId)) {
            criteria.andUnionIdEqualTo(unionId);
        }
        if (StringUtils.isNotBlank(openId)) {
            criteria.andOpenIdEqualTo(openId);
        }
        criteria.andTypeEqualTo(type);
        criteria.andIsDeleteEqualTo(Constants.BYTE_ZERO);
        List<TbUserThirdAccount> userThirdAccountList = userThirdAccountMapper.selectByExample(example);

        return userThirdAccountList;
    }

    /**
     * 插入用户第三方绑定
     * @param userThirdAccount
     * @return
     */
    public int insertUserThirdAccount(TbUserThirdAccount userThirdAccount) {
        int n = 0 ;
        if(userThirdAccount.getUid() != null)
            n = userThirdAccountExtendMapper.insertUserThirdAccount(userThirdAccount);
        return n;
    }

    /**
     * 删除用户第三方绑定
     * @param uid
     * @param larkAppId
     * @param type
     * @return
     */
    public int deleteUserThirdAccount(Integer uid,Integer larkAppId,Integer type){
        TbUserThirdAccountExample example = new TbUserThirdAccountExample();
        TbUserThirdAccountExample.Criteria criteria = example.createCriteria();
        criteria.andTypeEqualTo(type);
        criteria.andUidEqualTo(uid);
        criteria.andLarkAppIdEqualTo(larkAppId);
        TbUserThirdAccount userThirdAccount = new TbUserThirdAccount();
        userThirdAccount.setIsDelete(UserConstants.IS_DELETE_S);
        int n = userThirdAccountMapper.updateByExampleSelective(userThirdAccount, example);
        return n;
    }




}
